package org.qqcui.designpattern.patterns.prototype.deepclone;

import java.io.*;

import javax.lang.model.element.VariableElement;

/**
 * 需要深拷贝的对象类
 * 推荐使用序列化与反序列化方式进行深拷贝
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2020-10-18 11:54
 **/
public class DeepClone implements Serializable, Cloneable {

	public String name;

	public DeepCloneTarget deepCloneTarget;

	public final DeepCloneTarget finalTarget = new DeepCloneTarget("finalTarget", 3);

	/**
	 * 方式一，通过复写clone方法的模式，来实现引用对象的深拷贝
	 * @return
	 * @throws CloneNotSupportedException
	 */
	@Override
	protected Object clone() throws CloneNotSupportedException {
		Object obj = null;
		obj = super.clone();
		DeepClone deepClone = (DeepClone) obj;
		// 针对被拷贝对象中的所有引用类型属性，都需要进行拷贝处理
		deepClone.deepCloneTarget = (DeepCloneTarget) deepCloneTarget.clone();
		return deepClone;
	}


	/**
	 * 方式二，通过序列化与反序列化的方式来实现深拷贝
	 * 推荐使用序列化与反序列化的方式进行深拷贝
	 * @return
	 */
	public DeepClone deepClone() {
		DeepClone copy = null;
		ByteArrayOutputStream bos = null;
		ObjectOutputStream out = null;
		ByteArrayInputStream bis = null;
		ObjectInputStream in = null;
		try {
			bos = new ByteArrayOutputStream();
			out = new ObjectOutputStream(bos);
			out.writeObject(this);
			bis = new ByteArrayInputStream(bos.toByteArray());
			in = new ObjectInputStream(bis);
			copy = (DeepClone) in.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (bis != null) {
					bis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return copy;
	}
}
